<template>
  <div class="warp-box clearfix">
    <div class="warp-con">
      <div class="header">
        <div class="headerWrapper">
          <div class="search">
            <el-form :inline="true">
              <el-form-item>
                <el-input placeholder="种质名称" v-model="query.name" clearable />
              </el-form-item>
              <el-form-item>
                <el-date-picker v-model="query.time" type="daterange" :default-time="['00:00:00', '23:59:59']"
                                start-placeholder="育苗时间" range-separator="至" end-placeholder="育苗时间"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="primary" @click="add" v-if="addBtn">新增</el-button>
                <el-dropdown @command="exportTmpVal" class="exportMenu" trigger="click" v-if="exportBtn">
                  <el-button type="primary">
                    导出<i class="el-icon-arrow-down el-icon--right" />
                  </el-button>
                  <el-dropdown-menu slot="dropdown" style="background-color: rgb(21 120 176)">
                    <el-dropdown-item :command="false">
                      选择
                    </el-dropdown-item>
                    <el-dropdown-item :command="true">
                      全部
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="content">
        <el-table ref="multipleTable" border stripe v-loading="loading" :data="tableData" lement-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                  @select="handleSelect" @select-all="handleSelectAll" class="tableLine" :max-height="635">
          <el-table-column align="center" type="selection" v-if="exportBtn" />
          <el-table-column show-overflow-tooltip align="center" prop="name" label="种质名称" />
          <el-table-column show-overflow-tooltip align="center" prop="time" label="育苗时间" :formatter="dateFormat" />
          <el-table-column show-overflow-tooltip align="center" prop="contact" label="联系人" />
          <el-table-column show-overflow-tooltip align="center" prop="plantLocation" label="种植县区" />
          <el-table-column show-overflow-tooltip align="center" prop="quantity" label="数量" />
          <el-table-column show-overflow-tooltip align="center" prop="purpose" label="种植目的" />
          <el-table-column align="center" label="操作" :min-width="100">
            <template slot-scope="scope">
              <span @click="showDetail(scope.row)" class="pointer">查看</span>
              <span @click="update(scope.row)" class="pointer" v-if="updateBtn"><i class="line"></i>修改</span>
              <span @click="remove(scope.row)" class="pointer" v-if="deleteBtn"><i class="line"></i>删除</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination :page-sizes="[10,20,50]" :page-size="pageSize" :total="totalCount" @current-change="pager"
                       @size-change="handleSizeChange" background layout="total, sizes, prev, pager, next, jumper"/>
      </div>
    </div>

    <el-dialog :title="title" :visible.sync="dataVisible" :before-close="cancel" :close-on-click-modal="false">
      <el-form :model="dataForm" ref="ruleForm" class="demo-ruleForm">
        <div class="form-table">
          <table width="100%">
            <tr>
              <td class="form-item_label">种质名称</td>
              <td>
                <el-input class="td-input" v-model="dataForm.name" @focus="showSeedling" :disabled="operation!==1"/>
              </td>
              <td class="form-item_label">育苗时间</td>
              <td>
                <el-date-picker disabled v-model="dataForm.time" type="date"
                                format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"/>
              </td>
            </tr>
            <tr>
              <td>联系人</td>
              <td>
                <el-input class="td-input" v-model="dataForm.contact" :disabled="operation===3"/>
              </td>
              <td>种植区县</td>
              <td>
                <el-input class="td-input" v-model="dataForm.plantLocation" :disabled="operation===3"/>
              </td>
            </tr>
            <tr>
              <td class="form-item_label">数量</td>
              <td>
                <el-input-number v-model="dataForm.quantity" :precision="0" :min="0" :max="maxQuantity"
                                 :disabled="operation===3"/>
              </td>
              <td>种植目的</td>
              <td>
                <el-input class="td-input" v-model="dataForm.purpose" :disabled="operation===3"/>
              </td>
            </tr>
            <tr>
              <td style="display:table-cell;vertical-align:middle">其他情况说明</td>
              <td colspan="3">
                <el-input type="textarea" v-model="dataForm.explain" :disabled="operation===3"/>
              </td>
            </tr>
          </table>
          <div style="margin-top: 20px">
            <el-form-item label="图片上传:">
              <el-upload action="#" list-type="picture-card" :file-list="fileList" :auto-upload="false"
                         :on-change="handleChange" :accept="'image/*'" :disabled="operation===3">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{ file }">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" style="min-height: 146px"/>
                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span v-if="operation!==3" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <div class="preview">
                <el-dialog title="预览" :visible.sync="dialogVisible" :modal="false" width="1200px" top="50px">
                  <img :src="dialogImageUrl" alt=""/>
                </el-dialog>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save" class="dialogBtn" v-if="operation!==3">保 存</el-button>
        <el-button type="primary" @click="cancel" class="dialogBtn">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="苗木繁育" :visible.sync="seedlingVisible" class="import" :before-close="cancelSeedling" :close-on-click-modal="false">
      <div class="search">
        <el-form :inline="true">
          <el-form-item>
            <el-input placeholder="种质名称" v-model="query.name" clearable />
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="query.time" type="daterange" :default-time="['00:00:00', '23:59:59']"
                            start-placeholder="育苗时间" range-separator="至" end-placeholder="育苗时间"
                            format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="querySeedling">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content">
        <el-table v-loading="seedlingLoading" :data="seedlingTable" lement-loading-text="拼命加载中" @row-click="checkedTableRows"
                  element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" border>
          <el-table-column show-overflow-tooltip align="center" prop="name" label="种质名称" />
          <el-table-column show-overflow-tooltip align="center" prop="site" label="育苗地点" />
          <el-table-column show-overflow-tooltip align="center" prop="time" label="育苗时间" :formatter="dateFormat" />
          <el-table-column show-overflow-tooltip align="center" prop="age" label="苗龄" />
          <el-table-column show-overflow-tooltip align="center" prop="number" label="育苗数量" />
          <el-table-column show-overflow-tooltip align="center" prop="quantity" label="现存数量" />
        </el-table>
      </div>
      <div class="paging">
        <el-pagination :page-size="seedlingQuery.pageSize" :total="seedlingCount" background
                       @current-change="seedlingPager" layout="total, prev, pager, next, jumper"/>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
import resourceApi from '@/api/resourceApi'
import seedlingSizesApi from "../../../api/seedlingSizesApi";
import seedlingBreedingApi from "../../../api/seedlingBreedingApi";

export default {
  name: 'seedlingBreeding',
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: '',
      query: {},
      pageIndex: 1,
      pageSize: 10,
      totalCount: 0,
      tableData: [],
      loading: false,
      title: null,
      dataForm: {},
      operation: null,
      dataVisible: false,
      maxQuantity: 0,
      seedlingQuery: {
        name: null,
        pageIndex: 1,
        pageSize: 5
      },
      seedlingCount: 0,
      seedlingTable: [],
      seedlingVisible: false,
      seedlingLoading: false,
      addBtn: false,
      updateBtn: false,
      deleteBtn: false,
      exportBtn: false,
      onlyId: [],
      fileServerUrl: null,
      FILE_SERVER: process.env.FILE_SERVER
    }
  },
  created() {
    this.initBtn();
    this.findPage();
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList.push(file);
      if(!((file.raw.type === 'image/png' || file.raw.type === 'image/gif' || file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg' || file.raw.type === 'image/PNG' || file.raw.type === 'image/JPG' || file.raw.type === 'image/JPEG'))){
        this.handleRemove(file);
        this.$message({
          message: '只能上传图片文件',
          type: 'warning'
        });
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleRemove(file) {
      if (file.id) {
        this.$confirm('确定删除该附件吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          resourceApi.delGatherPic(file.id).then((res) => {
            if (res.data.messageCode === '200') {
              this.$notify({
                title: '消息',
                message: '删除成功！',
                position: 'bottom-right',
                showClose: false,
                type: 'success'
              })
              for (let i in this.fileList) {
                let item = this.fileList[i]
                if (item.id === file.id) {
                  this.fileList.splice(i, 1)
                  break
                }
              }
            }
          })
        })
      } else {
        this.fileList.forEach((item, index) => {
          if (item.uid === file.uid) {
            this.fileList.splice(index, 1)
          }
        })
      }
    },
    search() {
      this.pageIndex = 1;
      this.clearSelection();
      this.findPage();
    },
    findPage() {
      this.loading = true
      let params = {
        name: this.query.name,
        pageSize: this.pageSize,
        pageIndex: this.pageIndex,
        startTime: this.query.time ? this.query.time[0] : null,
        endTime: this.query.time ? this.query.time[1] : null
      }
      seedlingSizesApi.findPage(params).then(res => {
        this.loading = false
        let result = res.data.result
        if (res.data.message === 'success' && result) {
          this.totalCount = result.totalCount
          this.tableData = result.rows

          let onlyId = this.onlyId
          if (onlyId.length > 0) {
            this.$nextTick(() => {
              this.tableData.forEach((row) => {
                for (let i in onlyId) {
                  let id = onlyId[i];
                  if (row.id === id) {
                    this.$refs.multipleTable.toggleRowSelection(row);
                    break;
                  }
                }
              });
            });
          }
        } else {
          this.totalCount = 0
          this.tableData = []
        }
      })
    },
    pager(val) {
      this.pageIndex = val
      this.findPage()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.findPage()
    },
    dateFormat(row,column){
      let date = row[column.property];
      if(date == undefined){return ''};
      return moment(date).format("YYYY-MM-DD")
    },
    add() {
      this.title = '新增'
      this.operation = 1
      this.dataVisible = true
    },
    showDetail(row) {
      this.title = '查看'
      this.operation = 3
      seedlingSizesApi.getInfo(row).then(res => {
        if (res.data.message === 'success') {
          this.dataForm = res.data.result
          this.maxQuantity = this.dataForm.quantity
          this.dataForm.fileList.forEach((item) => {
            item.url = this.FILE_SERVER + item.path
            this.fileList.push(item)
          });
          this.dataVisible = true
        } else {
          this.dataForm = {}
        }
      })
    },
    save() {
      let name = this.dataForm.name
      if (!name || name.length < 1) {
        this.$message({
          message: '种质名称不能为空',
          type: 'warning'
        })
        return false
      }
      let time = this.dataForm.time
      if (!time) {
        this.$message({
          message: '育苗时间不能为空',
          type: 'warning'
        })
        return false
      }
      let quantity = this.dataForm.quantity
      if (!quantity) {
        this.$message({
          message: '出圃数量不能为空',
          type: 'warning'
        })
        return false
      }
      delete this.dataForm.fileList
      seedlingSizesApi.save(this.fromData(this.dataForm)).then(res => {
        if (res.data.message === 'success') {
          this.$notify({
            title: '消息',
            message: ('保存成功！'),
            position: 'bottom-right',
            showClose: false,
            type: 'success'
          })
          this.findPage()
          this.cancel()
        }
      })
    },
    fromData(form) {
      let formData = new FormData();
      for (let item of this.fileList) {
        if (item.raw) {
          formData.append("accessory", item.raw);
        }
      }
      for (let key in form) {
        if (form[key] == null || form[key] === "null") {
          form[key] = "";
        }
        formData.append(key, form[key]);
      }
      return formData;
    },
    update(row) {
      this.title = '修改'
      this.operation = 2
      this.getSeedling(row.breedingId).then(seedling => {
        if (seedling.data.message === 'success') {
          let result = seedling.data.result
          this.maxQuantity = result.number
          seedlingSizesApi.getInfo(row).then(res => {
            if (res.data.message === 'success') {
              this.dataForm = res.data.result
              this.dataForm.fileList.forEach((item) => {
                item.url = this.FILE_SERVER + item.path
                this.fileList.push(item)
              })
              console.log(this.fileList);
              this.dataVisible = true
            } else {
              this.dataForm = {}
            }
          })
        }
      })
    },
    remove(row) {
      let tips = ''
      if (row) {
        tips = `此操作将删除: ${row.name}, 是否继续?`
      } else {
        return false
      }
      this.$confirm(tips, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seedlingSizesApi.remove(row).then(res => {
          if (res.data.message === 'success') {
            this.findPage()
            this.$notify({
              title: '消息',
              message: ('删除成功！'),
              position: 'bottom-right',
              showClose: false,
              type: 'success'
            })
          }
        })
      }).catch(() => {})
    },
    cancel() {
      this.dataForm = {}
      this.fileList = []
      this.maxQuantity = 0
      this.dataVisible = false
    },
    showSeedling() {
      this.seedlingPage()
      this.seedlingVisible = true
    },
    querySeedling() {
      this.seedlingQuery.pageIndex = 1;
      this.seedlingPage();
    },
    seedlingPage() {
      this.seedlingLoading = true
      seedlingBreedingApi.findPage(this.seedlingQuery).then(res => {
        this.seedlingLoading = false
        let result = res.data.result
        if (res.data.message === 'success' && result) {
          this.seedlingCount = result.totalCount
          this.seedlingTable = result.rows
        } else {
          this.seedlingCount = 0
          this.seedlingTable = []
        }
      })
    },
    seedlingPager(val) {
      this.seedlingQuery.pageIndex = val
      this.seedlingPage()
    },
    cancelSeedling() {
      this.seedlingQuery = {
        name: null,
        pageIndex: 1,
        pageSize: 5
      }
      this.seedlingVisible = false
    },
    checkedTableRows(row, column, event) {
      this.$set(this.dataForm, 'quantity', 0)
      this.$set(this.dataForm, 'name', row.name)
      this.$set(this.dataForm, 'time', row.time)
      this.$set(this.dataForm, 'breedingId', row.id)
      this.maxQuantity = row.quantity
      this.cancelSeedling()
    },
    async getSeedling(val) {
      return await seedlingBreedingApi.getInfo({id:val})
    },
    initBtn() {
      let permissionBtn = JSON.parse(localStorage.permissionBtn)
      this.addBtn = permissionBtn['seedling_sizes_add']
      this.updateBtn = permissionBtn['seedling_sizes_update']
      this.deleteBtn = permissionBtn['seedling_sizes_delete']
      this.exportBtn = permissionBtn['seedling_sizes_export']
    },
    handleSelect(selection, row) {
      let id = row.id;
      let checked = false;
      for (let i in selection) {
        let item = selection[i];
        if (item.id === id) {
          checked = true;
          break;
        }
      }
      if (checked) {
        this.onlyId.push(id);
      } else {
        let index = this.onlyId.indexOf(id)
        this.onlyId.splice(index, 1);
      }
    },
    handleSelectAll(selection) {
      if (selection.length > 0) {
        for (let i in selection) {
          let item = selection[i]
          if (this.onlyId.indexOf(item.id) === -1) {
            this.onlyId.push(item.id)
          }
        }
      } else {
        let data = this.tableData
        for (let i in data) {
          let item = data[i]
          let index = this.onlyId.indexOf(item.id)
          if (index !== -1) {
            this.onlyId.splice(index, 1)
          }
        }
      }
    },
    clearSelection() {
      this.onlyId = []
      this.$refs.multipleTable.clearSelection()
    },
    async exportTmpVal(isAll) {
      if (!isAll) {
        if (this.onlyId.length === 0) {
          this.$message({
            message: "请选择需要导出的数据",
            type: "warning",
          });
          return false;
        }
      }

      let loading = this.$loading({
        lock: true,
        text: '数据导出中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      let time = this.query.time
      let params = {
        isAll: isAll,
        onlyId: this.onlyId,
        start: time ? time[0] : null,
        end: time ? time[1] : null,
        name: this.query.name
      }
      let url = '/gr/seedlingSizes/exportExcel'
      await resourceApi.downloadExcel(url, params)
      loading.close()
      this.clearSelection()
    }
  }
}
</script>
<style lang="less" scoped>
.search {
  & /deep/ .el-form-item__label {
    font-size: 1.8rem;
  }
}

/deep/ .el-dialog {
  min-width: 900px;
}

.form-table {
  width: 100%;

  table,
  tr,
  td {
    border: 1px solid #fff;
  }

  td {
    &:nth-child(even) {
      width: 32%;
    }

    &:nth-child(odd) {
      text-indent: 10px;
    }
  }

  /deep/ .el-input__inner {
    border: none;
  }
  /deep/ .el-textarea__inner {
    border: none;
  }

  .oblique {
    /deep/ .el-input__inner {
      font-style:oblique;
    }
  }
}

.el-form-item__label {
  padding: 0 20px 0 0 !important;
}

.content {
  margin-top: 10px;

  & /deep/ .el-checkbox__inner {
    height: 20px;
    width: 20px;
    font-size: 28px;
    font-weight: 400;
    color: rgba(255, 255, 255, 1);
    background: none;
  }

  & /deep/ .el-tooltip__popper {
    background-color: red;
  }

  & /deep/ .el-checkbox__inner::after {
    border-width: 2px;
    /* border-color: black; */
    height: 6px;
    left: 6px;
    top: 3px;
    width: 4px;
  }

  & /deep/ .el-checkbox__input.is-indeterminate .el-checkbox__inner::before {
    top: 8px;
    background: white;
  }
}

.line {
  display: inline-flex;
  height: 21px;
  width: 1px;
  background: rgba(0, 255, 255, 1);
  margin: 0 10px;
  vertical-align: middle;
}

.dialogBtn {
  font-size: 1.6rem;

  &:hover {
    background: rgba(12, 161, 151, 1);
  }
}

.coordinate {
  width: 25%;
}
.import {
  /deep/ .el-dialog__body {
    border-bottom: 1px solid #1f5aab;
  }
}
.exportMenu {
  margin-left: 10px;
}

/deep/ .el-dropdown-menu__item:focus,
.el-dropdown-menu__item:not(.is-disabled):hover {
  color: #ffffff;
  background-color: #32f1ff16;
}
</style>
<style lang="less">
/**
   * 修改样式   覆盖默认的饿了么全局样式
   */
.el-form-item__label {
  padding: 0 20px 0 0 !important;
}
</style>
